package cn.lycode.framework.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.lycode.common.core.controller.BaseController;
import cn.lycode.common.core.domain.AjaxResult;
import cn.lycode.common.core.domain.model.user.LoginBody;
import cn.lycode.framework.web.domain.LoginVO;
import cn.lycode.system.domain.vo.SysMenuVO;
import cn.lycode.framework.web.service.SysLoginService;
import cn.lycode.framework.web.service.SysPermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author lyCode
 */
@RestController
@RequiredArgsConstructor
public class SysLoginController extends BaseController {
    private final SysLoginService loginService;
    private final SysPermissionService permissionService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/login")
    public AjaxResult<LoginVO> login(@RequestBody LoginBody loginBody) {
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();
        String code = loginBody.getCode();
        String uuid = loginBody.getUuid();
        // 生成令牌
        LoginVO loginVo = loginService.login(username, password, code, uuid);
        return AjaxResult.success(loginVo);
    }

    /**
     * 查询用户具有的菜单
     * @return 用户具有的菜单
     */
    @SaIgnore
    @GetMapping("/user/menu")
    public AjaxResult<List<SysMenuVO> > queryMenuByUserId() {
        List<SysMenuVO> menuList = permissionService.findMenuListByUserId(getLoginUserId());
        return AjaxResult.success(menuList);
    }

    /**
     * 查询用户具备的所有按钮权限   前端项目需要这个信息来作为按钮展示权限
     * @return
     */
    @SaIgnore
    @GetMapping("/user/perms")
    public AjaxResult<Set<String>> queryBtnPermissionByUserId() {
        Set<String> perms = permissionService.getMenuPermission(getLoginUserId());
        return AjaxResult.success(perms);
    }


    /**
     * 查询用户角色  前端项目需要这个信息来进行路由过滤
     * @return 用户所有的角色名
     */
    @SaIgnore
    @GetMapping("/user/roles")
    public AjaxResult<Set<String>> queryUserRoles() {
        Set<String> roles = permissionService.getRolePermFlag(getLoginUserId());
        return AjaxResult.success(roles);
    }

    @PostMapping("/logout")
    public AjaxResult<Object> logout() {
        // 注意执行顺序，最后再执行logout
        StpUtil.getTokenSession().logout(); // 清除缓存session
        StpUtil.logout();   // 退出登录
        return AjaxResult.success();
    }

}
